package com.heima.article.interceptor;

import com.alibaba.fastjson.JSON;
import com.heima.article.utils.WmThreadLocalUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.entity.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppTokenInterceptor extends HandlerInterceptorAdapter {

    /**
     * 前置拦截, 目标控制器执行之前执行拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求中的用户ID userId
        String userId = request.getHeader("userId");
        //通过网关服务
        if (StringUtils.isNotBlank(userId)) {
            //2. 将用户信息保存到ThreadLocal
            ApUser apUser = new ApUser();
            apUser.setId(Long.valueOf(userId));

            WmThreadLocalUtil.set(apUser);

            return super.preHandle(request, response, handler);
        }

        //没有经过网关进行权限验证, 返回401 , 以及失败信息
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().write(JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH)));

        return false;
    }

    /**
     * 后置拦截, 目标控制器执行之后执行拦截
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清空ThreadLocal数据,防止内存泄露
        WmThreadLocalUtil.remove();
        super.postHandle(request, response, handler, modelAndView);
    }
}
